package com.aniu.smslisten.weixin;

import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

/**
 * 推送微信消息
 */
public class PushWorker extends Worker {
    private static final String TAG = "PushWorker";
    private static final String PUSH_API_URL = "https://wxpusher.zjiecode.com/api/send/message"; // 修改为HTTPS
    private static final String APP_TOKEN = "AT_99Yurkvog79KQsZ8nMoJivAR5xD4eG4G"; // 替换为你的appToken
    private static final String[] USERS = {"UID_QZv9Uu58XeOEShxR3sxp0fqKTcZK"}; // 替换为你的用户列表

    public PushWorker(@NonNull Context context, @NonNull WorkerParameters params) {
        super(context, params);
    }

    @NonNull
    @Override
    public Result doWork() {
        String message = getInputData().getString("message");
        if (message == null) {
            Log.e(TAG, "Message is null");
            return Result.failure();
        }
        if (message.length() > 40){
            message = message.substring(0, 40) + "...";
        }

        try {
            URL url = new URL(PUSH_API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            JSONObject jsonInput = new JSONObject();
            jsonInput.put("appToken", APP_TOKEN);
            jsonInput.put("content", message);
            jsonInput.put("contentType", 1); // 1表示文本消息
            jsonInput.put("uids", new org.json.JSONArray(USERS)); // 修改为直接传递数组
            jsonInput.put("url", "");

            String jsonInputString = jsonInput.toString();

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            Log.d(TAG, "Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                Log.d(TAG, "Message pushed successfully");
            } else {
                Log.e(TAG, "Error: " + connection.getResponseMessage());
            }
            return Result.success();
        } catch (Exception e) {
            Log.e(TAG, "Exception: ", e);
            return Result.retry();
        }
    }
}